package com.aggregate.pay.payeco.test.client;

import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aggregate.pay.common.RequestClient;
import com.aggregate.pay.payeco.Config;
import com.aggregate.pay.payeco.PayecoFactory;


public class ExampleRequestClient implements RequestClient {

	private static Logger log = LoggerFactory.getLogger(ExampleRequestClient.class);
	
	@Override
	public String request(String server, String queryString) {
		Config cfg = PayecoFactory.getConfig();
		Header header = new BasicHeader("Content-Type", 
				"application/x-www-form-urlencoded; charset=" + cfg.getDataEncode());
		HttpUriRequest httpUriRequest = RequestBuilder
				.post()
				.setHeader(header)
				.setUri(server + "/ppi/merchant/itf.do?" + queryString)
				.build();
		CloseableHttpClient httpClient = HttpClientFactory.createHttpClient();
		CloseableHttpResponse response;
		try {
			response = httpClient.execute(httpUriRequest);
			int status = response.getStatusLine().getStatusCode();
			log.debug("远程接口返回状态：{}", response.getStatusLine());
	        if (status == 200) {
				return EntityUtils.toString(response.getEntity(), cfg.getDataEncode());
	        } 
		} catch (Exception e) {
			log.error("远程接口调用失败", e);
		} 
		return null;
	}
}
